﻿    using System;
    using System.Collections;
    using HT.Framework;
    using TG.Timer;
    using UnityEditor.SceneManagement;
    using UnityEngine;
    using UnityEngine.SceneManagement;

    namespace TG
    {
        public class MainGame : HTBehaviour
        {
            private static MainGame instance;
            public static MainGame Instance
            {
                get
                {
                    if (instance == null)
                    {
                        Debug.LogError($"GameManager 未初始化！！！");
                    }
                    return instance;
                }
            }
            /// <summary>
            /// 配置表数据
            /// </summary>
            public GameConfigDatas GameConfig;
            
            /// <summary>
            /// 游戏配置数据
            /// </summary>
            public BaseGameConfig curGameConfig;

            public bool isRunning = false;
            public bool IsActive { get; set; }

            public float secondsTime;

            protected override void Awake()
            {
                base.Awake();
                instance = this;
                DontDestroyOnLoad(this);
                //设置配置
                GameSetting.ReadConfig();

                GameConfigHelper.LoadJianSuBi();
                curGameConfig = new BaseGameConfig();
                GameConfigHelper.LoadAllGameConfig(curGameConfig);
                
                //训练模式 读取上一轮记录数据
                if (curGameConfig.gameType == 1)//读取训练模式下本地保存文件
                    ReadPlayerPrefs();
                else//读取游戏配置
                    LoadAllGameConfig();
                
                BalanceInputManager.Instance.Initialize(ref curGameConfig);
                IsActive = true;
                GameManager.Instance.InitCurLevelData();
                StartCoroutine(Init());
                secondsTime = Time.time;
            }

            private void ReadPlayerPrefs()
            {
                //训练模式 读取上一轮记录数据
                if (curGameConfig.gameType == 1)
                {
                    if (PlayerPrefs.HasKey($"{curGameConfig.playName}_Time"))
                        curGameConfig.gameTime = PlayerPrefs.GetInt($"{curGameConfig.playName}_Time", 10);

                    if (PlayerPrefs.HasKey($"{curGameConfig.playName}_sensitivity"))
                        curGameConfig.sensitivity =
                            (SensitivityType)PlayerPrefs.GetInt($"{curGameConfig.playName}_sensitivity", 1);

                    if (PlayerPrefs.HasKey($"{curGameConfig.playName}_diff"))
                        curGameConfig.sensitivity =
                            (SensitivityType)PlayerPrefs.GetInt($"{curGameConfig.playName}_diff", 0);
                }
            }

            private void LoadAllGameConfig()
            {
                string infos = Resources.Load<TextAsset>("Json/GameConfigData").text;
                Debug.Log(infos.ToString());
                GameConfig = JsonUtility.FromJson<GameConfigDatas>(infos);
            }


            IEnumerator Init()
            {
                Main.m_Event.Throw(
                    Main.m_ReferencePool.Spawn<LoadingProgressChange>().Fill(0.4f, 1f));
                yield return PreLoadSomePanel();
                Main.m_Event.Throw(
                    Main.m_ReferencePool.Spawn<LoadingProgressChange>().Fill(0.6f, 0.8f));
                yield return LoadScene();
                Main.m_Event.Throw(
                    Main.m_ReferencePool.Spawn<LoadingProgressChange>().Fill(1f, 0.6f));
            }

            /// <summary>
            /// 预加载常用界面
            /// </summary>
            /// <returns></returns>
            IEnumerator PreLoadSomePanel()
            {
                yield return null;
            }

            /// <summary>
            /// 加载游戏场景
            /// </summary>
            /// <returns></returns>
            IEnumerator LoadScene()
            {
#if UNITY_EDITOR
                LoadSceneParameters parameters = new LoadSceneParameters()
                {
                    loadSceneMode = LoadSceneMode.Additive
                };
                EditorSceneManager.LoadSceneInPlayMode(Default.AssetPath, parameters);
                LoadSceneFinish();
#else
            SceneInfo asset = new SceneInfo(Default.assetBundleName, Default.assetPath, Default.sceneName);
            Main.m_Resource.LoadScene(asset, null, LoadSceneFinish);
#endif
                yield break;
            }

            private void LoadSceneFinish()
            {
                Main.m_Coroutiner.StartCoroutine(OnLoadDone());
                isRunning = true;
            }

            private IEnumerator OnLoadDone()
            {
                yield return new WaitForSeconds(2f);
                
                GameSetting.SetScreenDisplay();
                
                Main.m_Procedure.SwitchNextProcedure();

                Main.m_Event.Throw(
                    Main.m_ReferencePool.Spawn<LoadingProgressChange>().Fill(1f, 0, true));
            }

            private void Update()
            {
                if (!IsActive)return;
                
                TimerManager.Instance.OnFrameElapsed();
                if (!(Time.time - secondsTime >= 1)) return;
                secondsTime = Time.time;
                TimerManager.Instance.OnSecondsElapsed();
            }


            public void ExitScene()
            {
                IsActive = false;
                QuitGame();
            }

            /// <summary>
            /// 游戏结束清理完成
            /// </summary>
            private bool m_onClearEnd;

            private void ForceQuit()
            {
                StopAllCoroutines();
                Debug.Log("游戏不正常退出");
            }

            void Quit()
            {
                Debug.Log("游戏正常退出");
                StopAllCoroutines();
                Application.Quit();
            }

            void QuitGame()
            {
                Quit();
                m_onClearEnd = true;
            }

            private void OnApplicationQuit()
            {
                if (!m_onClearEnd)
                {
                    ForceQuit();
                }

                Main.m_Resource.UnLoadAllAsset(true);
                Main.m_Resource.UnLoadAllScene();
                Main.m_Resource.ClearMemory();
            }
        }
    }
